util = require 'util'
#例：2012-02-14 14:28:47
exports.getMysqlDateTimeFormat = (dateTime) ->
  return dateTime if not dateTime? or dateTime is ""
  dateTime = new Date dateTime unless dateTime instanceof Date
  "#{dateTime.getFullYear()}-#{dateTime.getMonth() + 1}-#{dateTime.getDate()} #{dateTime.getHours()}:#{dateTime.getMinutes()}:#{dateTime.getSeconds()}"

#例：2012-02-14
exports.getMysqlDateFormat = (dateTime) ->
  return dateTime if not dateTime? or dateTime is ""
  dateTime = new Date dateTime unless dateTime instanceof Date
  "#{dateTime.getFullYear()}-#{dateTime.getMonth() + 1}-#{dateTime.getDate()}"

# format (new Date (), "%Y-%m-%d %H:%M:%S", true) returns "2012-05-18 05:37:21"
exports.dateFormat = (date, fmt, utc=false)->
  utc = if utc then 'getUTC' else 'get'
  fmt.replace /%[YmdHMS]/g, (m)->
    switch (m)
      when '%Y' then return date[utc + 'FullYear']() # no leading zeros required
      when '%m' then m = 1 + date[utc + 'Month'](); break
      when '%d' then m = date[utc + 'Date'](); break
      when '%H' then m = date[utc + 'Hours'](); break
      when '%M' then m = date[utc + 'Minutes'](); break
      when '%S' then m = date[utc + 'Seconds'](); break
      else return m.slice(1) # unknown code, remove %
    # add leading zero if required
    return ('0' + m).slice(-2)

exports.ymdToDate = (ymd) ->
  new Date "#{ymd[0..3]}/#{ymd[4..5]}/#{ymd[6..7]}"

Date.prototype.addDays = (date,days) ->
  dt = date
  unless days
    dt = new Date()
    days = date
  new Date dt.getFullYear(),dt.getMonth(),dt.getDate()+days

Date.prototype.toYmdString = ->
  exports.dateFormat(this, "%Y%m%d")

Date.prototype.toDateString = ->
  exports.dateFormat(this, "%Y-%m-%d")

Date.prototype.toTimeString = ->
  exports.dateFormat(this, "%H:%M:%S")

Date.prototype.toDateTimeString = ->
  exports.dateFormat(this, "%Y-%m-%d %H:%M:%S")

Date.prototype.toJsDateTimeString = ->
  exports.dateFormat(this, "%Y/%m/%d %H:%M:%S")

exports.isDate = util.isDate